package fulbiNet.dao;


	import java.sql.Connection;
	import java.sql.PreparedStatement;
import java.sql.ResultSet;
	import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

	import fulbiNet.execpcion.DAOExcepcion;
	import fulbiNet.modelo.Local;
import fulbiNet.util.ConexionBD;

	public class LocalDAO extends BaseDAO {

		public void insertar(Local vo) throws DAOExcepcion {
			System.out.println("LocalDAO: insertar(Local vo)");
			String query = "INSERT INTO Local(nombre,telefono,idDistrito,Direccion) VALUES (?,?,?,?)";
			Connection con = null;
			PreparedStatement stmt = null;
			try {
				con = ConexionBD.obtenerConexion();
				stmt = con.prepareStatement(query);
				
				stmt.setString(1, vo.getNombre());
				stmt.setString(2, vo.getTelefono());
				stmt.setInt(3, vo.getoDistrito().getCodigo());
			    stmt.setString(4,vo.getDireccion());
							
				int i = stmt.executeUpdate();
				if (i != 1) {
					throw new SQLException("No se pudo insertar");
				}
			} catch (SQLException e) {
				System.err.println(e.getMessage());
				throw new DAOExcepcion(e.getMessage());
			} finally {
				this.cerrarStatement(stmt);
				this.cerrarConexion(con);
			}
		}

		
		public Collection<Local> listarPorNombre(String sNombre) throws DAOExcepcion
		{
			System.out.println("LocalDAO: listar()");
			Collection<Local> c = new ArrayList<Local>();
			Connection con = null;
			PreparedStatement stmt = null;
			ResultSet rs = null;
			try {
				con = ConexionBD.obtenerConexion();
				String query = "SELECT idLocal, nombre, telefono, iddistrito from Local where nombre = ?";
				stmt = con.prepareStatement(query);
				stmt.setString(1, sNombre);
				
				rs = stmt.executeQuery();
				
				while (rs.next()) {
					Local vo = new Local();
					
					vo.setCodigo(rs.getInt(1));
					vo.setNombre(rs.getString(2));
					vo.setTelefono(rs.getString(3));
				
					
					c.add(vo);
				}
			} catch (SQLException e) {
				System.err.println(e.getMessage());
				throw new DAOExcepcion(e.getMessage());
			} finally {
				this.cerrarStatement(stmt);
				this.cerrarConexion(con);
			}
			return c;
		}

	

	public int obtenerIdLocal() throws DAOExcepcion {
		System.out.println("LocalAO: obtener ultimo ID generado()");
		int idLocal=0;
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String query = "select MAX(idLocal) from local";
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				idLocal= rs.getInt(1);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return idLocal;
	}
	}
	